package leeon.bbsbrower.views;

import ipworks.IPWorksException;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import leeon.bbsbrower.actions.BBSConAction;
import leeon.bbsbrower.models.DocObject;
import leeon.bbsbrower.util.BrowerImages;
import leeon.bbsbrower.util.ImageDownloadManager;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;

public class ConView extends ViewPart {
	public static final String ID = "bbsbrower.view.con";

	private Text text = null;
	
	//从哪一篇文章进入
	private static int doc = 0;
	private static String url = null;
	
	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	public void createPartControl(Composite parent) {		
		
		//文章数据
		text = new Text(parent, SWT.V_SCROLL|SWT.READ_ONLY);
		text.setFont(ApplicationWorkbenchWindowAdvisor.listFont);		
				
		//上下左右的事件
		text.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
				//左
				if (e.keyCode == SWT.ARROW_LEFT) {
					actionToDoc();
					e.doit = false;
				//右，到最底或者最顶
				} else if (e.keyCode == SWT.ARROW_RIGHT) {
					//最顶
					if (text.getCaretLineNumber() == text.getLineCount()-1)
						text.setSelection(0, 0);
					//最底
					else
						text.append("");
					
					e.doit = false;
				//上，并且在第一行
				} else if (e.keyCode == SWT.ARROW_UP && text.getCaretLineNumber() == 0) {
					//获取上篇文章
					if (doc != 0) {
						actionGetUpDoc();
					//自动翻到前一页
					} else {
						actionGetPageUpDoc();
					}
					e.doit = false;
				//下，并且在最后一行
				} else if (e.keyCode == SWT.ARROW_DOWN && text.getCaretLineNumber() == text.getLineCount()-1) {
					//获取下篇文章
					if (doc != DocView.size - 1) {
						actionGetDownDoc();
					//自动翻到下一页
					} else {
						actionGetPageDownDoc();
					}
					e.doit = false;
				//回文章
				} else if (e.character == 'r') {
					actionReDoc();
					e.doit = false;
				//浏览整个页
				} else if (e.keyCode == SWT.END) {
					actionBrowser();
					e.doit = false;
				//弹出图片
				} else if (e.keyCode == SWT.CTRL) {
					actionImage();
					e.doit = false;
				} else if (e.keyCode == SWT.HOME) {
					actionAllImage();
					e.doit = false;
				}
			}

			public void keyReleased(KeyEvent e) {}
			
		});
	}
	
	
	/**
	 * 回文章列表
	 */
	private void actionToDoc() {		
		//跳转文章列表界面
		IWorkbenchPage page = this.getViewSite().getPage();
		page.hideView(this);
		try {
			DocView doc = (DocView)page.showView(DocView.ID);
			doc.refreshData(-1, null, null, ConView.doc, -1, null);
		} catch (PartInitException e) {
			e.printStackTrace();
		}	
	}
	
	
	/**
	 * 向下获取文章
	 *
	 */
	private void actionGetDownDoc() {
		DocObject doc = DocView.docs[ConView.doc+1];
		//置底的内容不进行读取
		if (!"[∞]".equals(doc.getNumber())) {
			refreshData(ConView.doc+1, doc.getURL());
		}		
	}
	
	/**
	 * 向下获取文章
	 *
	 */
	private void actionGetPageDownDoc() {
		DocView.actionToPageDown();	
		DocObject doc = DocView.docs[0];
		//置底的内容不进行读取
		if (!"[∞]".equals(doc.getNumber())) {
			refreshData(0, doc.getURL());
		}		
	}
	
	/**
	 * 向上获取文章
	 *
	 */
	private void actionGetPageUpDoc() {
		DocView.actionToPageUp();				
		DocObject doc = DocView.docs[DocView.size-1];
		//置底的内容不进行读取
		if (!"[∞]".equals(doc.getNumber())) {
			refreshData(DocView.size-1, doc.getURL());
		}		
	}
	
	/**
	 * 向上获取文章
	 *
	 */
	private void actionGetUpDoc() {
		DocObject doc = DocView.docs[ConView.doc-1];
		//置底的内容不进行读取
		if (!"[∞]".equals(doc.getNumber())) {
			refreshData(ConView.doc-1, doc.getURL());
		}		
	}
	
	/**
	 * 回文
	 *
	 */
	private void actionReDoc() {
		String bn = DocView.bname;
		String title = DocView.docs[doc].getTitle();
		
		IWorkbenchPage page = this.getViewSite().getPage();
		page.hideView(this);
		try {
			SendDocView doc = (SendDocView)page.showView(SendDocView.ID);
			doc.refreshData(1, bn, title, ConView.doc);
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 图片对话筐
	 *
	 */
	private void actionImage() {
		//定位行
		int s = text.getCaretPosition();
		String d = text.getLineDelimiter();
		int e = text.getText().indexOf(d, s);
		
		//查找url
		String line = (e==-1)?text.getText().substring(s):text.getText().substring(s, e);
		line = BrowerImages.findImageURL(line);
		String name = BrowerImages.dealImageName(line); 
		
		//有图片链接
		if (line != null) {
			int status = BrowerImages.getImageStatus(name);
			//没有
			if (status == 0) {
				//开始下载
				ImageDownloadManager manager = ImageDownloadManager.newInstance();
				manager.addImageUrl(line);
			
			//有,显示
			} else if (status == 2) {
				ImageDialog id = new ImageDialog(this.getViewSite().getShell(), new String[] {name});
				id.open();				
			}
		}
	}
	
	/**
	 * 全部图片对话框 
	 *
	 */
	private void actionAllImage() {
		//寻找http://bbs.fudan.edu.cn/cgi-bin/.....
		List<String> urlList = new ArrayList<String>();
		Pattern p = Pattern.compile("http://[\\.\\w-/]*\\.(JPG|GIF|BMP)");
		Matcher m = p.matcher(text.getText());
		while (m.find()) {
			String url = m.group();			
			boolean isSame = false;
			for (int i = 0; i < urlList.size(); i ++) {
				if (urlList.get(i).equals(url)) {
					isSame = true;
					break;
				}
			}
			if (!isSame) urlList.add(url);
		}
		
		boolean allOk = true;
		String[] names = new String[urlList.size()];
		List<String> namesList = new ArrayList<String>();
		ImageDownloadManager manager = ImageDownloadManager.newInstance();
		
		for (int i = 0; i < urlList.size(); i ++) {
			String url = urlList.get(i);
			names[i] = BrowerImages.dealImageName(url);
			
			int status = BrowerImages.getImageStatus(names[i]);
			//没有
			if (status == 0) {
				//开始下载
				manager.addImageUrl(url);
				allOk = false;
			//正在下载
			} else if (status == 1) {
				allOk = false;
			//坏链接和standby不作处理
			//但standby才能加入names列表
			} else if (status == 2) {
				namesList.add(names[i]);
			}
		}
		
		
		if (allOk) {
			ImageDialog id = new ImageDialog(this.getViewSite().getShell(), namesList.toArray(new String[0]));
			id.open();
		} else {
			ProgressMonitorDialog mo = new ProgressMonitorDialog(this.getViewSite().getShell());
			mo.open();
		}
	}
	
	private void actionBrowser() {
		BrowerDialog bd = new BrowerDialog(this.getViewSite().getShell(), ConView.url);
		bd.open();
		
	}
	
	public void refreshData(int doc, String url) {
		//根据url提取文章
		ConView.doc = doc;
		ConView.url = url;
				
		//设定值
		try {
			text.setText(BBSConAction.getDocContentByURL(url));
		} catch (IPWorksException e) {
			MessageDialog.openError(this.getViewSite().getShell(), "错误信息", e.toString());
			e.printStackTrace();
		}
		ApplicationActionBarAdvisor.setStatusLine();
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		text.setFocus();
	}
}